package otel;


import lombok.extern.slf4j.Slf4j;
import net.flyinggroup.spring.http.DefaultHttpRequest;
import net.flyinggroup.spring.http.reactive.HttpRequester;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@Slf4j
public class RollController {
    private final WebClient webClient;

    public RollController(WebClient.Builder builder) {
        this.webClient = builder.build();
    }

    @GetMapping("/rolldice")
    public List<Integer> rolldice(@RequestParam("player") Optional<String> player, @RequestParam("rolls") Optional<Integer> rolls) {
        if (rolls.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing rolls parameter", null);
        }
        List<Integer> result = new Dice(1, 6).roll(rolls.get());

        if (player.isPresent()) {
            log.info("{} is rolling the dice: {}", player.get(), result);
        } else {
            log.info("Anonymous player is rolling the dice: {}", result);
        }
        return result;
    }

    @GetMapping("/rollout")
    public List<Integer> rollout(@RequestParam("rolls") Optional<String> rolls) {
        DefaultHttpRequest request = DefaultHttpRequest.builder()
                .uri("http://localhost:8080/rolldice")
                .params(rolls.isPresent() ? Map.of("rolls", rolls.get()) : Collections.emptyMap())
                .build();
        Mono<List<Integer>> result = HttpRequester.getForMonoBody(webClient, request, List.class, Integer.class);
        return result.block();
    }
}
